package com.hiof.servercommunication.background.job;

import com.hiof.location.GPSManager;
import com.hiof.location.GpsMangerFactory;
import com.hiof.servercommunication.RestFulServiceManager;
import com.hiof.servercommunication.exception.NetworkException;
import com.hiof.servercommunication.exception.ServerException;
import com.hiof.servercommunication.receive.beans.AcknowledgePacket;
import com.hiof.servercommunication.receive.beans.GeoPoint;
import com.hiof.servercommunication.receive.beans.Packet;
import com.hiof.settings.user.TypeOfAttendant;
import com.hiof.settings.user.UserConfiguration;
import com.hiof.utility.Utility;

/**
 * Created by IntelliJ IDEA.
 * User: manish
 * Date: 4/1/12
 * Time: 12:27 PM
 * To change this template use File | Settings | File Templates.
 */
public class LiveLocationSendJob extends AbstractJob {

    @Override
    public Packet connect2Server() {
        int userId = UserConfiguration.getInstance().getUserId();
        int attendantId = UserConfiguration.getInstance().getAttendantId();
        AcknowledgePacket acknowledgePacket = new AcknowledgePacket("ok");
        try {
            GPSManager gpsManager =  GpsMangerFactory.getGpsManager();
            GeoPoint geoPoint = gpsManager.getLatestLocation();
            double speed = gpsManager.getLatestSpeed();
            if (UserConfiguration.getInstance().getTypeOfAttendant() == TypeOfAttendant.ATHLETE) {
                acknowledgePacket = RestFulServiceManager.getInstance().sendAthleteLocationInfo(userId, attendantId, geoPoint.getLat(),
                        geoPoint.getLng(), geoPoint.getAltitude(), speed);
            } else {
                acknowledgePacket = RestFulServiceManager.getInstance().sendSupportLocationInfo(userId, attendantId, geoPoint.getLat(),
                        geoPoint.getLng(), geoPoint.getAltitude(), speed);
            }
        } catch (NetworkException e) {
            Utility.error(this.getClass().toString(),"NetworkException when sending Live Location:"+e.getMessage());
            acknowledgePacket.setMessage("Network Exception");
        } catch (ServerException e) {
            Utility.error(this.getClass().toString(),"ServerException when sending Live Location:"+e.getMessage());
            acknowledgePacket.setMessage("Serve Exception");
        }
        Utility.debug(this.getClass().toString(),"packet:"+acknowledgePacket.getMessage());
        return acknowledgePacket;
    }

}
